import moment from 'moment';
import store from '../store';
export default {
    install(Vue) {
        var getSeries=function(echartsItem,list,type){
            var serises=[];
            if(list!=null&&list.length>0)
            {
                for(var i =0;i<list.length;i++)
                {
                    serises.push({
                        "name":echartsItem[i],
                        "type":type,
                        "data":list[i],
                        "markPoint":{
                            "data" : [
                                {
                                    "type" : 'max', "name": '最大值'
                                },
                                {
                                    "type" : 'min', "name": '最小值'
                                },
                                {
                                    "type" : 'avg', "name": '平均值'
                                }
                            ]
                        }
                    });
                }
            }
            return serises;
        };
        var TimeOption=function(TableName,echartsItem,list){
            var option=[];
            for(var i=0;i<list.length;i++){
                option.push({ 
                toolbox: {
                    show: true,
                    right: 20,
                    top: 'top',
                    itemSize:20,
                    itemGap:30,
                    color : ['#4b0082','#d2691e'],
                    backgroundColor: 'rgba(0,0,0,0)', // 工具箱背景颜色
                    borderColor: '#ccc',       // 工具箱边框颜色
                    borderWidth: 0,            // 工具箱边框线宽，单位px，默认为0（无边框）
                    padding: 5,                // 工具箱内边距，单位px，默认各方向内边距为5，
                    showTitle: true,
                    feature: {
                        restore: {color : 'black'},
                        magicType: {//动态类型切换
                            type: ['bar', 'line'],
                            color : 'black'
                        }
                    },
                   
                }, 
                calculable : true,
                xAxis:[
                    {
                        data:echartsItem, 
                        dataZoom : {
                            show : true,
                            realtime : true,
                            start : 20,
                            end : 80
                        },
                    }
                ],
                title:{
                    text:TableName,
                    top:0,
                    left:'center',
                    textStyle:{
                        color:'#3C4251',
                        fontWeight:'bold',
                        fontSize:20
                    }
                },
                series:[{data:list[i]}]});
            }
            return option;
        };
        //获取地图定位数据
        var convertData = function (GeoData,data) {
            var res = [];
            var GeoJson=JSON.parse(GeoData);
            for (var i = 0; i < data.length; i++) {
                var geoCoord = GeoJson[data[i].name];
                if (geoCoord) {
                    res.push({
                        name: data[i].name,
                        value: geoCoord.concat(data[i].value)
                    });
                }
            }
            return res;
        };
        var getMapSeries=function(GeoData,mapType,echartsItem,list){
            var series=[];
            if(list!=null&&list.length>0)
            {
                for(var i=0;i<list.length;i++)
                {
                    series.push({
                        name:echartsItem[i],
                        type: 'map',
                        roam: true,//地图是否随鼠标滑动而放大缩小
                        mapType: mapType,
                        aspectScale: 0.9,
                        border:0,
                        // showEffectOn: 'render',
                        // rippleEffect: {
                        //     brushType: 'stroke'
                        // },
                        hoverAnimation: true,
                        label: {
                            normal: {
                                show: true,//显示省份标签
                                formatter:function (params) {
                                    return params.name + '：'+ params.value ;
                                },
                                textStyle:{color:"#c71585"},//省份标签字体颜色
                                position: 'inside',
                                backgroundColor: '#fff',
                                padding: [4, 5],
                                borderRadius: 3,
                                borderWidth: 1,
                                borderColor: 'rgba(0,0,0,0.5)',
                                color: '#777',

                            },    
                            emphasis: {//对应的鼠标悬浮效果
                                show: true,
                                textStyle:{color:"#800080"}
                            } 
                        },
                        itemStyle: {
                            normal: {
                                borderWidth: 0.5,//区域边框宽度
                                borderColor: '#009fe8',//区域边框颜色
                                areaColor:"#ffefd5",//区域颜色
                            },
                            emphasis: {
                                // borderWidth: .5,
                                borderColor: '#4b0082',
                                areaColor:"#ffdead",
                            }
                        },
                        data:list[i],
                    });
                    series.push({
                        name:echartsItem[i],
                        type: 'effectScatter',
                        show:false,
                        coordinateSystem: 'geo',
                        roam: true,//地图是否随鼠标滑动而放大缩小
                        mapType: mapType,
                        // aspectScale: 1,
                        // border:0,
                        symbol:'pin',
                        symbolSize:40,
                        // large:true,
                        
                        // showEffectOn: 'render',
                        rippleEffect: {
                            brushType: 'stroke',
                            color:'#FFF'
                        },
                        hoverAnimation: true,
                        label: {
                            show:false
                        },
                        itemStyle: {
                            normal: {
                                shadowBlur: 20,
                                borderWidth: 0.5,//区域边框宽度
                                color:'#000',
                                // borderColor: '#009fe8',//区域边框颜色
                                areaColor:"#ffefd5",//区域颜色
                            },
                            emphasis: {
                                // borderWidth: .5,
                                borderColor: '#4b0082',
                                areaColor:"#ffdead",
                            }
                        },
                        data:convertData(GeoData,list[i].sort(function(a,b){return b.value-a.value;}).slice(0,4)),
                        zlevel: 1
                        
                    });
                }
            }
            return series;
        }
        //根据用户当前地区编码,获取地区信息
        Vue.prototype.SearchAreaList=function(AreaCode) {
            var areaCode = AreaCode;
            var areaList=[];
            if (areaCode != '530000000000' && areaCode != null) {
                var item = this.GetlocaStorage("areatreelist")[0];
                for (var i = 0; i < item.children.length; i++) {
                    if (item.children[i].value == areaCode) {
                        areaList.push(item.children[i]);
                    }
                }
            } else {
                areaList = this.GetlocaStorage("areatreelist");
            }
            return areaList[0].children;
        },
        //获取柱状图配置文件
        Vue.prototype.GetBarOption=function(TableName,AreaData,echartsItem,list,type){
            var Option={
                title: {
                    text: TableName,
                    top:0,
                    left:'center',
                    extStyle:{
                        color:'#3C4251',
                        fontWeight:'bold',
                        fontSize:20
                    }
                },
                tooltip : {
                    trigger: 'axis',
                    axisPointer : {            // 坐标轴指示器，坐标轴触发有效
                        type : 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                    },
                    label: {
                        show: true,
                        backgroundColor: '#333'
                    }
                },
                //工具箱
                toolbox: {
                    show: true,
                    orient: 'vertical',
                    left: 'left',
                    top: 'top',
                    itemSize:20,
                    itemGap:30,
                    feature: {
                        // dataZoom: {
                        //     yAxisIndex: 'none'
                        // },
                        // dataView: {readOnly: false},
                        restore: {},
                        saveAsImage: {},
                        // magicType: {//动态类型切换
                        //     type: ['bar', 'line']
                        // }
                    }
                },
                // dataZoom: [{
                //     startValue: '2014-06-01'
                // }, {
                //     type: 'inside'
                // }],
                calculable : true,
                //切换项
                legend: {
                    orient:'vertical',
                    left:'right',
                    data:echartsItem
                },
                xAxis : [
                    {
                        // position:'top',//x轴位置
                        name:'X',
                        type : 'category',
                        data : AreaData,
                        splitLine: {
                            lineStyle: {
                                type: 'dashed'
                            }
                        },
                        axisLabel: {  
                            interval:0,  
                            rotate:-15  
                        }
                    },
                    
                ],
                yAxis : [
                    {
                        name:'Y',
                        nameGap:10,
                        type : 'value',  
                    }
                ],
                series : getSeries(echartsItem,list,type)
            };
            return Option;
        },
        Vue.prototype.GetTimeOption=function(TableName,XData,echartsItem,list,type){  
            var Option={
                title: {
                    text: TableName,
                    top:0,
                    left:'center',textStyle:{
                        color:'#3C4251',
                        fontWeight:'bold',
                        fontSize:20
                    }
                },
                tooltip : {
                    trigger: 'axis',
                    axisPointer : {            // 坐标轴指示器，坐标轴触发有效
                        type : 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                    },
                    label: {
                        show: true,
                        backgroundColor: '#333'
                    }
                },
                //工具箱
                toolbox: {
                    show: true,
                    orient: 'vertical',
                    left: 'left',
                    top: 'top',
                    itemSize:20,
                    itemGap:30,
                    feature: {
                        // dataZoom: {
                        //     yAxisIndex: 'none'
                        // },
                        // dataView: {readOnly: false},
                        restore: {},
                        saveAsImage: {},
                        // magicType: {//动态类型切换
                        //     type: ['bar', 'line']
                        // }
                    }
                },
                dataZoom: {
                    id: 'dataZoomY',
                    type: 'inside',
                    filterMode: 'empty',
                    disabled:false,                         //是否停止组件的功能。
                    xAxisIndex:0,                           //设置 dataZoom-inside 组件控制的 x轴,可以用数组表示多个轴
                    // yAxisIndex:[0,2],                       //设置 dataZoom-inside 组件控制的 y轴,可以用数组表示多个轴
                    // radiusAxisIndex:3,                      //设置 dataZoom-inside 组件控制的 radius 轴,可以用数组表示多个轴
                    // angleAxisIndex:[0,2],                   //设置 dataZoom-inside 组件控制的 angle 轴,可以用数组表示多个轴
                    start: 0,                               //数据窗口范围的起始百分比,表示30%
                    end: 100,                                  //数据窗口范围的结束百分比,表示70%
                    // startValue:10,                           //数据窗口范围的起始数值
                    // endValue:100,                            //数据窗口范围的结束数值。
                    // orient:"horizontal",                    //布局方式是横还是竖。不仅是布局方式，对于直角坐标系而言，也决定了，缺省情况控制横向数轴还是纵向数轴。'horizontal'：水平。'vertical'：竖直。
                    zoomLock:false,                          //是否锁定选择区域（或叫做数据窗口）的大小。如果设置为 true 则锁定选择区域的大小，也就是说，只能平移，不能缩放。
                    throttle:100,                             //设置触发视图刷新的频率。单位为毫秒（ms）。
                    zoomOnMouseWheel:true,                   //如何触发缩放。可选值为：true：表示不按任何功能键，鼠标滚轮能触发缩放。false：表示鼠标滚轮不能触发缩放。'shift'：表示按住 shift 和鼠标滚轮能触发缩放。'ctrl'：表示按住 ctrl 和鼠标滚轮能触发缩放。'alt'：表示按住 alt 和鼠标滚轮能触发缩放。
                    moveOnMouseMove:true,                    //如何触发数据窗口平移。true：表示不按任何功能键，鼠标移动能触发数据窗口平移。false：表示鼠标滚轮不能触发缩放。'shift'：表示按住 shift 和鼠标移动能触发数据窗口平移。'ctrl'：表示按住 ctrl 和鼠标移动能触发数据窗口平移。'alt'：表示按住 alt 和鼠标移动能触发数据窗口平移。
                }
                ,
                calculable : true,
                //切换项
                legend: {
                    orient:'vertical',
                    left:'right',
                    data:echartsItem,
                    selectedMode: 'single'
                },
                xAxis : [
                    {
                        // position:'top',//x轴位置
                        name:'X',
                        type : 'category',
                        data : XData,
                        splitLine: {
                            lineStyle: {
                                type: 'dashed'
                            }
                        },
                        axisLabel: {  
                            interval:0,  
                            rotate:-15  
                        }
                    },
                    
                ],
                yAxis : [
                    {
                        name:'Y',
                        nameGap:10,
                        type : 'value',  
                    }
                ],
                series : getSeries(echartsItem,list,type)
            };
            return Option;
        },
        Vue.prototype.GetMapOption=function(TableName,GeoData,mapType,echartsItem,list){
            var option = {
                title: {text: TableName,top:0,left:'center',textStyle:{
                    color:'#3C4251',
                    fontWeight:'bold',
                    fontSize:20
                }},
                // backgroundColor:'#F8F8F9',
                tooltip: {
                    backgroundColor:"#ff7f50",//提示标签背景颜色
                    textStyle:{color:"#fff"} //提示标签字体颜色
                },
                legend: {
                    orient:'vertical',
                    left:'right',
                    data:echartsItem,//数据集
                    selectedMode: 'single',
                },
                geo: {
                    map:  mapType,
                    aspectScale: 0.9,
                    label: {
                        emphasis: {
                            // show: false
                        }
                    },
                    roam: true,
                },
                toolbox: {
                    show: true,
                    orient: 'vertical',
                    left: 'left',
                    top: 'top',
                    itemSize:20,
                    itemGap:30,
                    feature: {
                        dataView: {readOnly: false},
                        restore: {},
                        saveAsImage: {}
                    }
                },
                visualMap: {
                    show:true,
                    // type: 'continuous',
                    type:'piecewise', 
                    splitNumber:20,
                    pieces:[
                        {min:0,max:5},
                        {min:0,max:50},
                        {min:0,max:500},
                        {min:0,max:1000},
                        {min:0,max:3000},
                        {min:0,max:5000},
                        {min:0,max:10000},
                        {min:0,max:50000},
                        {min:0,max:100000},
                        {min:0,max:150000},
                        {min:0,max:250000},
                        {min:0,max:500000}
                    ],
                    calculable : true,
                    min: 0,
                    max: '500000',
                    text:['最大值','最小值'],
                    realtime: false,
                    calculable: true,
                    inRange: {
                        color: ['white','lightskyblue','yellow','#FFCC00','orange','orangered'],
                        // symbolSize: [30, 100]
                    },
                    bottom:'bottom'
                },
                series:getMapSeries(GeoData,mapType,echartsItem,list)
            };
            return option;
        },
        //获取地图Geo数据
        Vue.prototype.GetGeoData=function(AreaCode){
            var areaList=this.SearchAreaList(AreaCode);
            var GeoData="";
            if(areaList!=null)
            {
                GeoData="{";
                for(var i=0;i<areaList.length;i++)
                {
                    if(i<areaList.length-1){
                        GeoData+="\""+areaList[i].FullName+"\":"+areaList[i].coord+",";
                    }
                    else{
                        GeoData+="\""+areaList[i].FullName+"\":"+areaList[i].coord;
                    }
                }
                GeoData+="}"; 
            }
            return GeoData;
        },
        Vue.directive('omg-operation', function(el, binding) {
                var keyVal = binding.value.op;
                var actions = store.state.ActionInfo.list;
                var account = store.state.ActionInfo.Account;
                var has = false;
                if (account != 'admin') {
                    for (var i = 0; i < actions.length; i++) {
                        if (actions[i].ActionCode == keyVal) {
                            has = true;
                        }
                    }
                    if (!has) {
                        el.style.display = "none";
                    }
                }
        }),
        Vue.directive('omg-set-menu-height', function(el, binding) {
            var height = 0;
            window.onresize = function() {
                height = window.innerHeight * 1 - 110;
                el.style.height = height + 'px';
            }
            height = window.innerHeight * 1 - 110;
            el.style.height = height + 'px';
        }),
        Vue.filter("omgConvStatus", function(val) {
            if (val * 1 === 1) {
                return '启用';
            } else {
                return '停用';
            }
        }),
        //保留一位小数
        Vue.filter("decimal", function(value,length) {
            if(isNaN(value)){
                return 0;
            }else{
                if(length==1){
                    value = parseFloat(value).toFixed(1);
                    if (value.toString().indexOf(".") < 0) {
                        value = value.toString() + ".0";
                    }
                    return value;
                }else{
                    value = parseFloat(value).toFixed(1);
                    var xsd = value.toString().split(".");
                    //Ext.log(xsd.length);
                    if(xsd.length==1){
                        value = value.toString()+".0";
                        return value;
                    }
                    if(xsd.length>1){
                        if(xsd[1].length<2){
                            value = value.toString();
                        }
                        return value;
                    }
                }
            }
        }),
        //整数
        Vue.filter("integer", function(value) {
            if (value == null || isNaN(value) || value == "Infinity") {
                return 0;
            } else {
                value =parseFloat(value).toFixed(0) ;
                return value;
            }
        }),
        Vue.filter("moment", function(value, formatString) {
            if (value == null) {
                return "";
            } else {
                formatString = formatString || 'YYYY-MM-DD';
                return moment(value).format(formatString);
            }
        }),
        Vue.filter("omgConvDict", function(val, groupCode) {
            var result = "";
            var dictlist = JSON.parse(window.localStorage.getItem("dictlist"));
            if (dictlist.length != 0) {
                for (var i = 0; i < dictlist.length; i++) {
                    if (dictlist[i].GroupCode == groupCode && dictlist[i].DictValue == val) {
                        result = dictlist[i].DictText;
                    }
                }
            }
            return result;
        }),
        Vue.filter("GetInterCropName", function(val) {
            var result = "";
            var dictlist = JSON.parse(window.localStorage.getItem("dictlist"));
            if (dictlist.length != 0) {
                for (var i = 0; i < dictlist.length; i++) {
                    if (dictlist[i].GroupCode == 'InterCrop' && dictlist[i].DictValue == val) {
                        result = dictlist[i].DictText;
                    }
                }
            }
            return result;
        }),
        //科学计数法
        Vue.filter("formatCurrency",function(num){
            var result="";
            if(num!=null)
            {
                ///科学计数法(保留两位小数)
                // num = num.toString().replace(/\$|\,/g,'');  
                // if(isNaN(num))  
                //     num = "0";  
                // var sign = (num == (num = Math.abs(num)));  
                // num = Math.floor(num*100+0.50000000001);  
                // var cents = num%100;  
                // num = Math.floor(num/100).toString();  
                // if(cents<10)  
                // cents = "0" + cents;  
                // for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)  
                // num = num.substring(0,num.length-(4*i+3))+','+  
                // num.substring(num.length-(4*i+3));  
                // return (((sign)?'':'-') + num + '.' + cents); 
                var n=0;
                var t = "";
                var len= num.toString().split(".").length;
                if(len>1){
                    n=num.toString().split(".")[1].length;
                }
                num = parseFloat((num + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";  
                var l = num.split(".")[0].split("").reverse(), r = num.split(".")[1];  

                for (var i = 0; i < l.length; i++) {  
                    t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");  
                }
                if(len>1)  
                {
                    result= t.split("").reverse().join("") + "." + r; 
                }
                else{
                    result=t.split("").reverse().join("") ; 
                }     
            }
            return result;
        }),
        Vue.filter("omgAreaName", function(val) {
            var result = "";
            var list = JSON.parse(window.localStorage.getItem("arealist"));
            if (list.length != 0) {
                for (var i = 0; i < list.length; i++) {
                    if (list[i].Code == val) {
                        result = list[i].Name;
                    }
                }
            }
            return result;
        }),
        Vue.prototype.SetlocaStorage = function(strkey, obj) {
            if (window.localStorage) {
                window.localStorage.setItem(strkey, JSON.stringify(obj));
            } else {
                alert("浏览暂不支持localStorage")
            }
        },
        Vue.prototype.GetlocaStorage = function(strkey) {
            if (window.localStorage) {
                return JSON.parse(window.localStorage.getItem(strkey));
            } else {
                alert("浏览暂不支持localStorage")
            }
        },
        Vue.prototype.GetGroupDict = function(groupCode) {
            //需要传入分组代码groupCode
            var dictlist = JSON.parse(window.localStorage.getItem("dictlist"));
            var resultlist = [];
            if (dictlist.length != 0) {
                for (var i = 0; i < dictlist.length; i++) {
                    if (dictlist[i].GroupCode == groupCode) {
                        resultlist.push(dictlist[i]);
                    }
                }
            }
            return resultlist;
        },
        Vue.prototype.GetCurrentYear=function(){
            var  CurrentDate = new Date();  
            var x=3;//加减月份的数量
            CurrentDate.setMonth(CurrentDate.getMonth()+1-x);  
            var nd = CurrentDate.valueOf() ;  
            nd = new Date(nd);          
            var y = nd.getFullYear();  
            return y;  
        },
        Vue.prototype.GetArea = function(parentCode) {
            //需要传入分组代码groupCode
            var list = JSON.parse(window.localStorage.getItem("arealist"));
            var resultlist = [];
            if (list.length != 0) {
                for (var i = 0; i < list.length; i++) {
                    if (list[i].ParentCode == parentCode) {
                        resultlist.push(list[i]);
                    }
                }
            }
            return resultlist;
        }
    }
}